package com.xbongbong.paas.statistics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.dao.PaasFormDataDao;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.StatisticPaasFormDataEsEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.BiRelTableEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.statistic.pojo.dto.AunInsertTestDTO;
import com.xbongbong.pro.statistic.pojo.dto.AunTestDTO;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * 测试阿里云ES代码
 * @author 梁鲁江
 * @version v1.0
 * @date 2019/6/17 17:21
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/chart/aliyun")
public class AliyunElasticDemoController {
    private static final Logger LOG = LoggerFactory.getLogger(AliyunElasticDemoController.class);
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private PaasFormDataDao paasFormDataDao;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private EsHelper esHelper;

    Long idIncr = 0L;
    @RequestMapping(value = "/test", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String test(@RequestBody @Valid AunTestDTO aunTestDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            PaasFormDataEntityExt entity = null;
            try {
                String esId = "";
                String data = "{\"text_18\":\"\",\"text_1\":\"测试客户11\",\"text_19\":\"\",\"text_16\":\"1\",\"date_2\":0,\"date_4\":1560586557,\"subForm_1\":[{\"text_1\":\"0\",\"text_2\":\"112123\"}],\"text_3\":\"\",\"num_8\":2,\"text_4\":\"\",\"num_1\":0,\"num_3\":0,\"text_8\":\"\"}";
                entity = new PaasFormDataEntityExt();
                long now = DateUtil.getNow();
                entity.setAddTime(now);
                entity.setAppId(5000001L);
                entity.setCorpid(aunTestDTO.getCorpid());
                entity.setCreatorId("1");
                entity.setData(JSON.parseObject(data));
                entity.setDataId(idIncr++);
                entity.setDepartmentId(1L);
                LOG.info("插入数量"+ esId);
                entity.setEsId(esId);
                entity.setId(idIncr);
                entity.setFlowStatus(9);
                entity.setFormId(5000001L);
                entity.setMenuId(5000001L);
                entity.setUpdateTime(now);
                entity.setSerialNo("SO.100002");
                entity.setOwnerId("1");
                InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_FORM_DATA);
                insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                paasEsModel.insert(insertDTO);
                response=  new XbbResponse<>(entity.getCorpid() + "_" + entity.getId());
            } catch (Exception e) {
                LOG.error("单纯插入报错",e);
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "单纯插入报错");
            }
        }
        response=  new XbbResponse<>(response);
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/syncTest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String syncTest(@RequestBody @Valid BaseDTO aunTestDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            PaasFormDataEntityExt entity = null;
            try {
                String esId = "";
                entity = new PaasFormDataEntityExt();
                long now = DateUtil.getNow();
                entity.setAddTime(now);
                entity.setAppId(5000001L);
                entity.setCorpid("-1"+"_"+aunTestDTO.getCorpid());
                entity.setCreatorId("1");
                entity.setData(new JSONObject());
                entity.setDataId(1L);
                entity.setDepartmentId(1L);
                LOG.info("插入数量"+ esId);
                entity.setEsId(esId);
                entity.setId(1L);
                entity.setFlowStatus(9);
                entity.setFormId(1L);
                entity.setMenuId(5000001L);
                entity.setUpdateTime(now);
                entity.setSerialNo("SO.100002");
                entity.setOwnerId("1");
                InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_FORM_DATA);
                insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                paasEsModel.insert(insertDTO);

                int b= 1;
                for(int i=0;i<1000;i++){
                    b = b+i;
                }
                System.out.println("====b===="+b);

                entity.setAddTime(1L);
  /*              paasFormDataDao.insert(entity);
                for(int i=0;i<1000;i++){
//                    PaasFormDataEntityExt innerEntity = paasFormDataModel.getByKey(entity.getId(), entity.getCorpid());
                    Long addTime = entity.getAddTime();
                    addTime = addTime + i;
                    entity.setAddTime(addTime);
                    paasFormDataDao.update(entity);
                }*/
//                PaasFormDataEntityExt dbInnerEntity = paasFormDataModel.getByKey(entity.getId(), entity.getCorpid());
//                System.out.println("=====dbInnerEntity.getAddTime()===="+dbInnerEntity.getAddTime());


                entity.setId(1L);
                entity.setDataId(1L);
                entity.setFormId(1L);
                paasEsModel.update(entity, IndexTypeEnum.IDX_FORM_DATA,entity.getCorpid(), entity.getId(),null);
                for(int i=0;i<1000;i++){
                    PaasFormDataEntityExt innerEntity = paasEsModel.getByKey(entity.getId(), entity.getCorpid(), IndexTypeEnum.IDX_FORM_DATA, null);
                    Long formId = innerEntity.getFormId();
                    formId = formId + i;
                    innerEntity.setFormId(formId);
                    paasEsModel.update(innerEntity, IndexTypeEnum.IDX_FORM_DATA,innerEntity.getCorpid(), innerEntity.getId(),null);
                }
                PaasFormDataEntityExt innerEntity = paasEsModel.getByKey(entity.getDataId(), entity.getCorpid(), IndexTypeEnum.IDX_FORM_DATA, null);
                System.out.println("=====innerEntity.getFormId()===="+innerEntity.getFormId());

                response=  new XbbResponse<>(entity.getCorpid() + "_" + entity.getId());
            } catch (Exception e) {
                LOG.error("一致性测试报错",e);
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "单纯插入报错");
            }
        }
        response=  new XbbResponse<>(response);
        return JSON.toJSONString(response);
    }


    @RequestMapping(value = "/insert", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String insert(@RequestBody @Valid AunInsertTestDTO aunInsertTestDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            CustomerEntityExt entity = null;
           try {
                entity =  customerModel.getByKey(aunInsertTestDTO.getId(), aunInsertTestDTO.getCorpid());
               entity.setDataId(entity.getId());
               customerModel.update(entity);
               if(true){
                   return null;
               }
                JSONObject data = entity.getData();
               List<PaasFormDataEntity>  list = new ArrayList<>();
                for(int i= 1;i<=1;i++){
                    String name = data.getString(CustomerManagementEnum.NAME.getAttr());
                    data.put(CustomerManagementEnum.NAME.getAttr(), name + 1);
                    String shortName = data.getString(CustomerManagementEnum.NAME_SHORT.getAttr());
                    data.put(CustomerManagementEnum.NAME_SHORT.getAttr(), shortName + 1);
                    //TODO
                    JSONArray phone = data.getJSONArray(CustomerManagementEnum.PHONE.getAttr());
                    if(CollectionsUtil.isNotEmpty(phone)){
                        JSONObject jsonObject = phone.getJSONObject(0);
                        String phoneNum = jsonObject.getString("text_2") + 1;
                        jsonObject.put("text_2",phoneNum);
                        data.put(CustomerManagementEnum.PHONE.getAttr(),phone);
                    }
                    int max = 2;
                    int min = 0;
                    int random = (int) (Math.random() * (max - min + 1)) + min;
                    data.put(CustomerManagementEnum.GENRE.getAttr(), random);
                    data.put(CustomerManagementEnum.TYPE.getAttr(), random);
                    data.put(CustomerManagementEnum.IS_INDIVIDUAL.getAttr(), random);
                    data.put(CustomerManagementEnum.SCALE.getAttr(), random);
                    data.put(CustomerManagementEnum.INDUSTRY.getAttr(), random);
                    data.put(CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(), random);

                    entity.setData(data);
                    entity.setId(null);
                    list.add(entity);
                }
               customerModel.insertBatch(list, false);
               response = new XbbResponse<>(entity.getCorpid() + "_" + entity.getId());
            } catch (Exception e) {
                LOG.error("模拟数据报错",e);
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "单纯插入报错");
            }
        }
        response=  new XbbResponse<>(response);
        return JSON.toJSONString(response);
    }

//    @RequestMapping(value = "/change/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String changeTest(  @Valid BaseDTO baseDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {

           try {
               SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
               BoolQueryBuilder boolQueryBuilder = boolQuery();
               boolQueryBuilder.filter(termQuery("corpid.keyword","1"));
               boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_FORM_DATA.getType()));
               sourceBuilder.query(boolQueryBuilder);
               //分页
               PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 1);
               SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_FORM_DATA.getIndex());
               searchRequest.source(sourceBuilder);
               XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
               System.out.println("esEntities===="+esEntities);
               esHelper.removeSearchCondition(boolQueryBuilder, "corpid.keyword");
               esHelper.removeSearchCondition(boolQueryBuilder, ElasticConstant.MY_JOIN_FIELD);
               boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, BiRelTableEnum.IDX_STATISTIC_CONTRACT_PRODUCT.getType()));
               boolQueryBuilder.filter(termQuery("corpid.keyword","xbbeca04bd4dba344ccb44090042b33809a"));
               searchRequest = new SearchRequest(BiRelTableEnum.IDX_STATISTIC_CONTRACT_PRODUCT.getIndex());
               searchRequest.source(sourceBuilder);
               XbbAggregatedPage<StatisticPaasFormDataEsEntity> biesEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, StatisticPaasFormDataEsEntity.class);
               System.out.println("biesEntities===="+ biesEntities);
               response = new XbbResponse<>("");
            } catch (Exception e) {
                LOG.error("切换错误",e);
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "切换错误");
            }
        }
        response=  new XbbResponse<>(response);
        return JSON.toJSONString(response);
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i=0;i<1000000000;i++){
            boolean ethry = BiRelTableEnum.inHere("nullidx_statistic_pass_data");
        }
        long midTime = System.currentTimeMillis();
        System.out.println( midTime-startTime);
        System.out.println(midTime);
        for(int i=0;i<1000000000;i++){
//            boolean ethry = BiRelTableEnum.inHeres("nullidx_statistic_pass_data");
        }
        long endTime = System.currentTimeMillis();
        System.out.println( endTime-midTime);
        System.out.println(endTime);
    }
}
